/*
 * @Descripttion: 
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2023-02-27 16:08:44
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2024-02-07 16:10:46
 */
const { Code, CodeMessage } = require('../constants/code')
const logger = require('./logger')
const { setCache } = require('../middleware/cache/index')


// 默认成功响应
function commonRes(res, data, options) {

  options = Object.assign({ type: Code[200] }, options || {}) // 默认success

  const { type, status, message } = options

  // 响应参数
  const sendRes = {
    code: Code[status] || 200,
    data,
  }
  // 响应描述
  message && (sendRes.message = message)

  setCache(res.req, sendRes)

  return res.status(200).send(sendRes)
}

// 错误响应
commonRes.error = function (res, data, message, status) {
  logger.error(message || CodeMessage['error'])
  this(res, data, { type: 'error', message: message || CodeMessage['error'], status: status || 409 })
}

// 无权限响应
commonRes.denied = function (res, data) {
  this(res, data, { type: 'denied', message: CodeMessage['denied'], status: 401 })
}

module.exports = commonRes